/**
 * @author Created by qiush on 2017-06-09.
 */

const fs = require('fs');
const path = require('path');

const fileUtil = {
  readFile(filename) {
    return new Promise((resolve, reject) => {
      fs.readFile(filename, 'UTF-8', (err, fileData) => {
        if (err) {
          reject(err);
        } else {
          resolve(fileData);
        }
      });
    });
  },

  writeFile(filename, jsonData) {
    return new Promise((resolve, reject) => {
      fs.writeFile(filename, JSON.stringify(jsonData), {
        encoding: 'UTF-8'
      }, err => {
        if (err) {
          reject(err);
        } else {
          resolve(filename);
        }
      });
    });
  },

  readBinaryFile(filename) {
    return new Promise((resolve, reject) => {
      fs.readFile(filename, (err, fileData) => {
        if (err) {
          reject(err);
        } else {
          resolve(fileData);
        }
      });
    });
  },

  writeBinaryFile(filename, data) {
    return new Promise((resolve, reject) => {
      fs.writeFile(filename, data, err => {
        if (err) {
          reject(err);
        } else {
          resolve(filename);
        }
      });
    });
  },

  isExist(file) {
    return new Promise((resolve) => {
      fs.access(file, (err) => {
        if (err) {
          resolve(false);
        } else {
          resolve(true);
        }
      })
    })
  },

  filename(file) {
    return path.basename(file);
  },

  mkdir(dir) {
    return new Promise((resolve, reject) => {
      fs.mkdir(dir, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(true);
        }
      })
    })
  },

  readDir(dir) {
    return new Promise((resolve, reject) => {
      fs.readdir(dir, (err, files) => {
        if (err) {
          reject(err);
        } else {
          resolve(files);
        }
      })
    })
  }

};

module.exports = fileUtil;
